package com.shop.cereshop.app.controller.follow;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.buyer.FollowUserListVo;
import com.shop.cereshop.commons.domain.buyer.FollowUserVo;
import com.shop.cereshop.commons.domain.im.tx.req.follow.*;
import com.shop.cereshop.commons.domain.im.tx.req.friend.GetSpecifyFriendReq;
import com.shop.cereshop.commons.domain.im.tx.resp.follow.FollowGetInfoResp;
import com.shop.cereshop.commons.domain.im.tx.resp.follow.FollowGetResp;
import com.shop.cereshop.commons.domain.im.tx.resp.follow.FollowUserResp;
import com.shop.cereshop.commons.domain.im.tx.resp.follow.GetSpecifyFriendResp;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.service.im.ImUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("follow")
@Api(value = "关注模块", tags = "关注模块")
public class FollowController {
    @Resource
    private ImUserService imUserService;

    @Resource
    private CereBuyerUserService cereBuyerUserService;

    /*@ApiOperation(value = "关注用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountUserId", value = "关注用户ID", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("followAdd")
    public Result followAdd(String accountUserId, HttpServletRequest request) {
        //获取当前登录账户
        CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
        if (BeanUtil.isEmpty(user)) {
            return new Result(CoReturnFormat.USER_NOT_LOGIN);
        }
        FollowAddReq req = new FollowAddReq();
        req.setFrom_Account(String.valueOf(user.getBuyerUserId()));
        req.setFollowItem(new FollowAddReq.FollowItem[]{
                new FollowAddReq.FollowItem(accountUserId)
        });
        FollowUserResp followUserResp = imUserService.followAdd(req);
        if (StrUtil.equals("OK", followUserResp.getActionStatus())) {
            for (FollowUserResp.FollowAdd followAdd : followUserResp.getResultItem()) {
                if (0 == followAdd.getResultCode()) {
                    return new Result(true, CoReturnFormat.SUCCESS);
                }
            }
        }
        return new Result(false, CoReturnFormat.FOLLOW_NULL);
    }*/

    @ApiOperation(value = "取消/关注用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountUserId", value = "取消关注用户ID", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "取消关注：0 关注：1 ", required = true, dataType = "Integer", paramType = "query")
    })
    @PostMapping("followAddOrDelete")
    public Result followDelete(String accountUserId,
                               Integer type,
                               HttpServletRequest request) {
        CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
        if (BeanUtil.isEmpty(user)) {
            return new Result(CoReturnFormat.USER_NOT_LOGIN);
        }
        Integer ifAllowOther = user.getIfAllowOther();
        if (ifAllowOther==0){
            return new Result(CoReturnFormat.NOT_ALLOW_FOLLOW_USER);
        }
        if (type == 0) {
            FollowDeleteReq req = new FollowDeleteReq();
            req.setFrom_Account(String.valueOf(user.getBuyerUserId()));
            req.setTo_Account(new String[]{accountUserId});
            FollowUserResp followUserResp = imUserService.followDelete(req);
            if (StrUtil.equals("OK", followUserResp.getActionStatus())) {
                for (FollowUserResp.FollowAdd followAdd : followUserResp.getResultItem()) {
                    if (0 == followAdd.getResultCode()) {
                        return new Result(true, CoReturnFormat.SUCCESS);
                    }
                }
            }
        } else if (type == 1) {
            FollowAddReq req = new FollowAddReq();
            req.setFrom_Account(String.valueOf(user.getBuyerUserId()));
            req.setFollowItem(new FollowAddReq.FollowItem[]{
                    new FollowAddReq.FollowItem(accountUserId)
            });
            FollowUserResp followUserResp = imUserService.followAdd(req);
            if (StrUtil.equals("OK", followUserResp.getActionStatus())) {
                for (FollowUserResp.FollowAdd followAdd : followUserResp.getResultItem()) {
                    if (0 == followAdd.getResultCode()) {
                        return new Result(true, CoReturnFormat.SUCCESS);
                    }
                }
            }
        }
        return new Result(false, CoReturnFormat.FOLLOW_NULL);
    }

    /**
     * 拉取关注、粉丝与互关列表
     */
    @ApiOperation(value = "拉取关注、粉丝与互关列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "查询类型： 1 粉丝 2 关注 3 互关 ", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "分页游标", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每次拉取的个数", required = true, dataType = "Integer", paramType = "query")
    })
    @GetMapping("getFollowList")
    public Result getFollowList(Integer type,
                                @RequestParam(required = false) String page,
                                Integer pageSize,
                                HttpServletRequest request) {
        CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
        if (BeanUtil.isEmpty(user)) {
            return new Result(CoReturnFormat.USER_NOT_LOGIN);
        }
        FollowGetReq req = new FollowGetReq();
        req.setFrom_Account(String.valueOf(user.getBuyerUserId()));
        //1 - 粉丝
        //2 - 关注
        //3 - 互关
        req.setFollowType(type);
        req.setStartCursor(page);
        req.setWantNum(pageSize);
        FollowGetResp followGetResp = imUserService.getFollowList(req);
        if (StrUtil.equals("OK", followGetResp.getActionStatus())) {
            if (CollUtil.isNotEmpty(followGetResp.getFollowItem())) {
                //提取关注列表accountUserId
                List<String> userIdList = followGetResp.getFollowItem().stream().map(FollowGetResp.FollowGet::getTo_Account).collect(Collectors.toList());
                List<CereBuyerUser> CereBuyerUserList = cereBuyerUserService.selectByBuyerUserIds(userIdList, null);
                GetSpecifyFriendReq friendReq = new GetSpecifyFriendReq();
                friendReq.setFromAccount(String.valueOf(user.getBuyerUserId()));
                //userIdList 转string数组
                friendReq.setToAccount(userIdList.toArray(new String[0]));
                GetSpecifyFriendResp friendBaseResp = imUserService.getSpecifyFriend(friendReq);


                FollowCheckReq checkReq = new FollowCheckReq();
                checkReq.setFrom_Account(String.valueOf(user.getBuyerUserId()));
                checkReq.setTo_Account(userIdList.toArray(new String[0]));
                FollowUserResp followUserResp = imUserService.followCheck(checkReq);
                Map<String, Integer> checkMap = new HashMap<>();
                if (StrUtil.equals("OK", followUserResp.getActionStatus())) {
                    if (CollUtil.isNotEmpty(followUserResp.getResultItem())) {
                        List<FollowUserResp.FollowAdd> resultItem = followUserResp.getResultItem();
                        for (FollowUserResp.FollowAdd followAdd : resultItem) {
                            checkMap.put(followAdd.getTo_Account(), followAdd.getFollowType());
                        }
                    }
                }
                List<String> friendIdList = new ArrayList<>();
                if (StrUtil.equals("OK", friendBaseResp.getActionStatus())) {
                    if (CollUtil.isNotEmpty(friendBaseResp.getInfoItem())) {
                        friendIdList = friendBaseResp.getInfoItem().stream().filter(item -> item.getResultCode() == 0).map(GetSpecifyFriendResp.GetSpecifyFriendItem::getTo_Account).collect(Collectors.toList());
                    }
                }
                List<FollowUserVo> followUserList = new ArrayList<>();
                for (CereBuyerUser cereBuyerUser : CereBuyerUserList) {
                    FollowUserVo followUserVo = new FollowUserVo();
                    followUserVo.setUserId(cereBuyerUser.getBuyerUserId());
                    followUserVo.setName(cereBuyerUser.getName());
                    followUserVo.setRemark(cereBuyerUser.getRemark());
                    followUserVo.setHeadImage(cereBuyerUser.getHeadImage());
                    Integer followType = checkMap.get(String.valueOf(cereBuyerUser.getBuyerUserId()));
                    if (null != followType) {
                        switch (followType) {
                            case 1:
                                followUserVo.setIsFans(1);
                                break;
                            case 2:
                                followUserVo.setIsFollow(1);
                                break;
                            case 3:
                                followUserVo.setIsMutual(1);
                                followUserVo.setIsFollow(1);
                                followUserVo.setIsFans(1);
                                break;
                        }
                    }
                    if (friendIdList.contains(String.valueOf(cereBuyerUser.getBuyerUserId()))) {
                        followUserVo.setIsFriend(1);
                    } else {
                        followUserVo.setIsFriend(0);
                    }
                    followUserList.add(followUserVo);
                }
                return new Result(new FollowUserListVo(followUserList, followGetResp.getNextCursor()), CoReturnFormat.SUCCESS);
            }
        }
        return new Result(new FollowUserListVo(null, followGetResp.getNextCursor()), CoReturnFormat.SUCCESS);
    }

    @ApiOperation(value = "检查关注关系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountUserId", value = "检测用户id", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("followCheck")
    public Result followCheck(String accountUserId, HttpServletRequest request) {
        CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
        if (BeanUtil.isEmpty(user)) {
            return new Result(CoReturnFormat.USER_NOT_LOGIN);
        }
        FollowCheckReq req = new FollowCheckReq();
        req.setFrom_Account(String.valueOf(user.getBuyerUserId()));
        req.setTo_Account(new String[]{accountUserId});
        FollowUserResp followUserResp = imUserService.followCheck(req);
        if (StrUtil.equals("OK", followUserResp.getActionStatus())) {
            if (CollUtil.isNotEmpty(followUserResp.getResultItem())) {
                FollowUserResp.FollowAdd followAdd = followUserResp.getResultItem().get(0);
                return new Result(followAdd, CoReturnFormat.SUCCESS);
            }
        }
        return new Result(false, CoReturnFormat.FOLLOW_NULL);
    }

    /**
     * 获取用户的关注、粉丝与互关数
     */
    @ApiOperation(value = "获取用户的关注、粉丝与互关数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountUserId", value = "检测用户id", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("followInfo")
    public Result getFollowInfo(String accountUserId, HttpServletRequest request) {
        CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
        if (BeanUtil.isEmpty(user)) {
            return new Result(CoReturnFormat.USER_NOT_LOGIN);
        }
        FollowGetInfoReq req = new FollowGetInfoReq();
        req.setFrom_Account(String.valueOf(user.getBuyerUserId()));
        req.setTo_Account(new String[]{accountUserId});
        FollowGetInfoResp followInfo = imUserService.getFollowInfo(req);
        if (StrUtil.equals("OK", followInfo.getActionStatus())) {
            if (CollUtil.isNotEmpty(followInfo.getFollowInfo())) {
                if (CollUtil.isNotEmpty(followInfo.getFollowInfo())) {
                    return new Result(followInfo.getFollowInfo().get(0), CoReturnFormat.SUCCESS);
                }
            }
        }
        return new Result(false, CoReturnFormat.FOLLOW_NULL);
    }

}
